package com.cys.markdown.doc.admin.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;

/**
 * Referer拦截器
 */
public class RefererInterceptor extends HandlerInterceptorAdapter {

    private final static Logger logger = LoggerFactory.getLogger(RefererInterceptor.class);

    @Value("${http.referer.ip}")
    private String ipAddress;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String referer = req.getHeader("referer");
        String host = req.getServerName();
        if (referer == null) {
            // 状态置为404
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }
        java.net.URL url = null;
        try {
            url = new java.net.URL(referer);
        } catch (MalformedURLException e) {
            // URL解析异常，也置为404
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }
        // 首先判断请求域名和referer域名是否相同
        if (!host.equals(url.getHost())) {
            List<String> allowOriginIpList = Arrays.asList(ipAddress.split(","));
            if (allowOriginIpList.contains(url.getHost())) {
                return true;
            }
            return false;
        }
        return true;
    }


}
